package com.blankland.dataanalysis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blankland.dataanalysis.domain.Device;
import com.blankland.dataanalysis.domain.GammaAnalyseData;
import com.blankland.dataanalysis.domain.GammaData;
import com.blankland.dataanalysis.result.Result;
import com.blankland.dataanalysis.service.DeviceService;
import com.blankland.dataanalysis.service.GammaAnalyseDataService;
import com.blankland.dataanalysis.service.GammaDataService;
import com.blankland.dataanalysis.service.impl.GammaDataServiceImpl;
import com.blankland.dataanalysis.utls.DataAnalysisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import java.util.HashMap;
import java.util.List;
import java.util.WeakHashMap;

@Api(tags = "能谱数据接口")
@RestController
@RequestMapping("/admin/system/gammaData")
public class GammaDataController {


    @Autowired
    private GammaDataService gammaDataService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private GammaAnalyseDataService gammaAnalyseDataService;


    @ApiOperation("查询：1、设备数量；2、能谱数量；3、解析能谱数量；4、未解析能谱数量")
    @GetMapping("/deviceNum")
    public Result getDeviceNum(){
        HashMap<String, Object> map = new HashMap<>();
        //1、设备数量
        long deviceCount = deviceService.count();
        //2、能谱数量
        long gammaCount = gammaDataService.count();
        //3、解析能谱数量
        QueryWrapper<GammaData> wrapper = new QueryWrapper<>();
        wrapper.eq("is_analysis",1);
        int gammaAnalyseCount = gammaDataService.list(wrapper).size();
        //4、未解析能谱数据
        QueryWrapper<GammaData> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("is_analysis",0);
        int gammaNoAnalyseCount = gammaDataService.list(wrapper1).size();

        map.put("deviceCount",deviceCount);
        map.put("gammaCount",gammaCount);
        map.put("gammaAnalyseCount",gammaAnalyseCount);
        map.put("gammaNoAnalyseCount",gammaNoAnalyseCount);


        return Result.ok(map);
    }


    @ApiOperation("分页查询")
    @GetMapping("/findDeviceByPageAndCondition")
    public Result findDeviceByPageAndCondition(@RequestParam Integer pageNum,
                                               @RequestParam Integer pageSize,
                                               @RequestParam(defaultValue = "") String deviceName){
        Page<Device> devicePage = new Page<>(pageNum,pageSize);
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.like("device_name",deviceName);


        Page<Device> page = deviceService.page(devicePage,wrapper);

        List<Device> records = page.getRecords();

        for (Device device : records) {
            Long deviceId = device.getDeviceId();
            //每台设备接收到多少数据
            QueryWrapper<GammaData> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("device_id",deviceId);
            device.setGammaDataNum(gammaDataService.count(wrapper1));

            //每台设备解析了多少数据
            QueryWrapper<GammaData> wrapper2 = new QueryWrapper<>();
            wrapper2.eq( "device_id",deviceId);
            wrapper2.eq("is_analysis",1);
            device.setGammaDataAnalyseNum(gammaDataService.count(wrapper2));

            //每台设备没有解析多少条数据
            QueryWrapper<GammaData> wrapper3 = new QueryWrapper<>();
            wrapper3.eq( "device_id",deviceId);
            wrapper3.eq("is_analysis",0);
            device.setGammaDataNoAnalyseNum(gammaDataService.count(wrapper3));
        }
            return Result.ok(page);
    }



    @ApiOperation("分页查询")
    @GetMapping("/findGammaDataByPage")
    public Result findGammaDataByPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize){

        Page<GammaData> gammaDataPage = new Page<>(pageNum,pageSize);
        Page<GammaData> page = gammaDataService.page(gammaDataPage);
        return Result.ok(page);
    }





    @ApiOperation("分页查询+模糊查询")
    @GetMapping("/findGammaDataByPageAndCondition")
    public Result findGammaDataByPageAndCondition(@RequestParam Integer pageNum,
                                                  @RequestParam Integer pageSize,
                                                  @RequestParam Integer deviceId){

        Page<GammaData> gammaDataPage = new Page<>(pageNum,pageSize);

        QueryWrapper<GammaData> wrapper = new QueryWrapper<>();
        wrapper.like("device_id",deviceId);

        Page<GammaData> page = gammaDataService.page(gammaDataPage,wrapper);
        return Result.ok(page);
    }




    @ApiOperation("查询每个设备：接收到多少条数据")
    @GetMapping("/getGammaDataByDevice")
    public Result getGammaDataByDevice(){
        List<Device> list = deviceService.list();

        HashMap<Long, Integer> map = new HashMap<>();

        for (Device device : list) {
            QueryWrapper<GammaData> gammaDataQueryWrapper = new QueryWrapper<>();
            gammaDataQueryWrapper.eq("device_id",device.getDeviceId());
            List<GammaData> gammaDataList = gammaDataService.list(gammaDataQueryWrapper);

            map.put(device.getDeviceId(),gammaDataList.size());
        }
        return Result.ok(map);
    }


    @ApiOperation("查询每个设备：解析了多少条数据")
    @GetMapping("/analyseGammaDataByDevice")
    public Result AnalyseGammaDataByDevice(){
        List<Device> list = deviceService.list();

        HashMap<Long, Integer> map = new HashMap<>();
        for (Device device : list) {
            QueryWrapper<GammaData> gammaDataQueryWrapper = new QueryWrapper<>();
            gammaDataQueryWrapper.eq("is_analysis",1);
            gammaDataQueryWrapper.eq("device_id",device.getDeviceId());
            List<GammaData> gammaDataList = gammaDataService.list(gammaDataQueryWrapper);
            map.put(device.getDeviceId(),gammaDataList.size());
        }
        return Result.ok(map);
    }


    @ApiOperation("查询每个设备：未解析了多少条数据")
    @GetMapping("/noAnalyseGammaDataByDevice")
    public Result noAnalyseGammaDataByDevice(){
        List<Device> list = deviceService.list();

        HashMap<Long, Integer> map = new HashMap<>();
        for (Device device : list) {
            QueryWrapper<GammaData> gammaDataQueryWrapper = new QueryWrapper<>();
            gammaDataQueryWrapper.eq("is_analysis",0);
            gammaDataQueryWrapper.eq("device_id",device.getDeviceId());
            List<GammaData> gammaDataList = gammaDataService.list(gammaDataQueryWrapper);
            map.put(device.getDeviceId(),gammaDataList.size());
        }
        return Result.ok(map);
    }

    @ApiOperation("一共多少条谱线数据")
    @GetMapping("/getGammaDataNum")
    public Result getGammaDataNum(){
        long count = gammaDataService.count();
        return Result.ok(count);
    }


    /**
     * 需要参数
     *  设备的id
     * @param deviceId
     * @return
     */
    @ApiOperation("原始谱线数据解析成18个特征向量")
    @GetMapping("/updateSpectralLineTo18Feature")
    public Result updateSpectralLineTo18Feature(Long deviceId){
        // 1 获取设备参数k、b、未解析数据list
        Device device = deviceService.getById(deviceId);
        Double k = device.getK();
        Double b = device.getB();
        QueryWrapper<GammaData> gammaDataQueryWrapper = new QueryWrapper<>();
        gammaDataQueryWrapper.eq("device_id", deviceId);
        List<GammaData> list = gammaDataService.list(gammaDataQueryWrapper);

        // 2 封装数据（谱线数据一列一列）
        // 2.1 参数1：原始谱线数据1025个字段（行），list.size()（列）
        int[][] spectrum = new int[1025][list.size()];
        // 2.2 参数2：经度
        double[] longitude = new double[list.size()];
        // 2.3 参数3：纬度
        double[] latitude = new double[list.size()];
        // 2.4 将数据库中的原始谱线，格式转成数组
        for (int i = 0; i < list.size(); i++) {
            //原始谱线数据
            String spectLine = list.get(i).getSpectLine();
            //去头去尾
            String spectLineSubstring = spectLine.substring(1, spectLine.length() - 1);
            String[] spectLineSplit = spectLineSubstring.split(",");
            for (int j = 0; j < spectLineSplit.length; j++) {
                spectrum[j][i] = Integer.parseInt(spectLineSplit[j]);
            }
            //经度
            longitude[i] = Double.valueOf(list.get(i).getLongitude());
            //纬度
            latitude[i] =Double.valueOf(list.get(i).getLatitude());
        }

        // 3 使用工具类解析数据
        double[][] geCharVal = DataAnalysisUtil.NaI2HPGeCharVal(k,b,spectrum, longitude, latitude);

        // 4 遍历结果，先列后行
//        for (int i = 0; i < geCharVal[0].length; i++) {
//            for (int j = 0; j < 20; j++) {
//                System.out.print(geCharVal[j][i]);
//                System.out.println("     ");
//            }
//            System.out.println("----------------");
//        }

        // 5 sess_gamma_data表is_analyse字段设置为1
        for (GammaData gammaData : list) {
            gammaData.setIsAnalysis(1);
            gammaDataService.updateById(gammaData);
        }


        // 6 解析完数据入库sess_gamma_analyse

        for (int i = 0; i < geCharVal[0].length; i++) {
            GammaAnalyseData gammaAnalyseData = new GammaAnalyseData();
            gammaAnalyseData.setDeviceId(deviceId);
            gammaAnalyseData.setLongitude(String.valueOf(geCharVal[0][i]));
            gammaAnalyseData.setLatitude(String.valueOf(geCharVal[1][i]));
            gammaAnalyseData.setVal1(geCharVal[2][i]);
            gammaAnalyseData.setVal2(geCharVal[3][i]);
            gammaAnalyseData.setVal3(geCharVal[4][i]);
            gammaAnalyseData.setVal4(geCharVal[5][i]);
            gammaAnalyseData.setVal5(geCharVal[6][i]);

            gammaAnalyseData.setVal6(geCharVal[7][i]);
            gammaAnalyseData.setVal7(geCharVal[8][i]);
            gammaAnalyseData.setVal8(geCharVal[9][i]);
            gammaAnalyseData.setVal9(geCharVal[10][i]);
            gammaAnalyseData.setVal10(geCharVal[11][i]);

            gammaAnalyseData.setVal11(geCharVal[12][i]);
            gammaAnalyseData.setVal12(geCharVal[13][i]);
            gammaAnalyseData.setVal13(geCharVal[14][i]);
            gammaAnalyseData.setVal14(geCharVal[15][i]);
            gammaAnalyseData.setVal15(geCharVal[16][i]);

            gammaAnalyseData.setVal16(geCharVal[17][i]);
            gammaAnalyseData.setVal17(geCharVal[18][i]);
            gammaAnalyseData.setVal18(geCharVal[19][i]);

            gammaAnalyseDataService.save(gammaAnalyseData);
        }

        return Result.ok(200 );


    }








}
